package com.nth.rooster.core.exception;

import java.io.BufferedInputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResponseErrorHandler;

/**
 * @Description This class handles the error thrown by Rest Template and send as
 *              user defined Exceptions return back to the rest client.
 * 
 */
public class CustomResponseErrorHandler implements ResponseErrorHandler {
	static Logger LOGGER = Logger.getLogger(CustomResponseErrorHandler.class);

	private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();

	/**
	 * This method process the response if the response has error and throw
	 * symphony exception.
	 * 
	 * @param response
	 *            ClientHttpResponse
	 * 
	 * @throws IOException
	 */
	public void handleError(ClientHttpResponse response) throws IOException {

		LOGGER.info("Entered::CustomResponseErrorHandler::handleError");
		
		String errorMessage = null;
		String errorKey = null;
		StringBuilder responseBody = new StringBuilder();
		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				response.getBody());

		while (bufferedInputStream.available() > 0) {
			responseBody.append((char) bufferedInputStream.read());
		}

		bufferedInputStream.close();

		try {
			JSONObject json = new JSONObject(responseBody.toString());

			errorKey = (String) json.get("errorKey");

			errorMessage = (String) json.get("message");

			errorHandler.handleError(response);

		} catch (Exception exception) {
			throw new RoosterCoreException(exception,
					NErrorCode.UNDEFINED_EXCEPTION);

		}
		
		LOGGER.info("Exited::CustomResponseErrorHandler::handleError");
	}

	/**
	 * This method calls the method handleError(ClientHttpResponse response)if
	 * this returns true.
	 * 
	 * @param response
	 *            ClientHttpResponse
	 * 
	 * @throws IOException
	 */
	public boolean hasError(ClientHttpResponse response) throws IOException {

		return errorHandler.hasError(response);
	}

}